package tq.com.tqstudent.widgets;

import android.app.Activity;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.target.SimpleTarget;
import com.bumptech.glide.request.transition.Transition;
import com.github.chrisbanes.photoview.PhotoView;
import com.lib.common.utils.ImgUtils;
import com.lib.common.utils.PermissionConstant;
import com.lib.common.utils.Tips;
import com.lib.common.utils.statusbar.StatusBarCompat;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.model.Response;
import com.yanzhenjie.permission.Action;
import com.yanzhenjie.permission.AndPermission;

import java.util.ArrayList;
import java.util.List;

import tq.com.tqstudent.App;
import tq.com.tqstudent.Constants;
import tq.com.tqstudent.R;
import tq.com.tqstudent.net.ok.StringCallback;

/**
 * @Author rames
 * @date 2019/4/22 17:49
 */
public class PreviewImgActivity extends AppCompatActivity {
    ViewPager viewpager;
    TextView indexTV;
    private int index;
    private int id; // 主要是为了给后台统计浏览次数用.不需要统计的就传0
    private boolean isNetUrl; // 不是网络图片就是本地图片
    private ArrayList<String> picList;

    public static void show(Activity activity, String url, int id){
        ArrayList<String> list = new ArrayList<>();
        list.add(url);
        show(activity, list, 0, id);
    }

    public static void show(Activity activity, ArrayList<String> picList, int index, int id) {
        show(activity, picList, index, true, id);
    }

    private static void show(Activity activity, ArrayList<String> picList, int index, boolean isNetUrl, int id) {
        Intent intent = new Intent(activity, PreviewImgActivity.class);
        Bundle bundle = new Bundle();
        bundle.putStringArrayList("picList", picList);
        bundle.putInt("index", index);
        bundle.putBoolean("isNetUrl", isNetUrl);
        bundle.putInt("id", id);
        intent.putExtras(bundle);
        activity.startActivity(intent);
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        StatusBarCompat.setStatusBarColor(this, getResources().getColor(R.color.black));

        setContentView(R.layout.activity_preview_img);
        if(null != getIntent() && null != getIntent().getExtras()){
            Bundle bundle = getIntent().getExtras();
            id = bundle.getInt("id", 0);
            isNetUrl = bundle.getBoolean("isNetUrl", true);
            picList = bundle.getStringArrayList("picList");
            index = bundle.getInt("index", 0);
        }

        initView(savedInstanceState);

        if(id != 0) {
            recodeTimes(id + "");
        }
    }

    public void initView(Bundle savedInstanceState) {
        indexTV = findViewById(R.id.index_tv);
        viewpager = findViewById(R.id.viewpager);

        indexTV.setText(index+"/"+(!isNetUrl ? "1" : picList.size()));
        ViewPagerAdapter adapter = new ViewPagerAdapter(this, picList);
        viewpager.setAdapter(adapter);
        viewpager.setCurrentItem(index);

        viewpager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int i, float v, int i1) {
                indexTV.setText((i+1)+"/"+picList.size());
            }

            @Override
            public void onPageSelected(int i) {

            }

            @Override
            public void onPageScrollStateChanged(int i) {

            }
        });
    }

    class ViewPagerAdapter extends PagerAdapter {
        private List<String> images;
        private Context context;

        /**
         * 构造方法，传入图片列表和ViewPager实例
         *
         * @param images
         */

        public ViewPagerAdapter(Context context, List<String> images) {
            this.context = context;
            this.images = images;
        }

        @Override
        public int getCount() {
            return images == null ? 0 : images.size();//返回一个无限大的值，可以 无限循环
        }

        /**
         * 判断是否使用缓存, 如果返回的是true, 使用缓存. 不去调用instantiateItem方法创建一个新的对象
         */
        @Override
        public boolean isViewFromObject(View view, Object object) {
            return view == object;
        }

        /**
         * 初始化一个条目
         *
         * @param container
         * @param position  当前需要加载条目的索引
         * @return
         */
        @Override
        public Object instantiateItem(ViewGroup container, int position) {
            // 把position对应位置的ImageView添加到ViewPager中
            View view = LayoutInflater.from(context).inflate(R.layout.item_preview_img, container, false);
            PhotoView iv = view.findViewById(R.id.image);
            iv.setOnClickListener(view1 -> PreviewImgActivity.this.finish());
            final Bitmap[] bitmap = new Bitmap[1];

//            if(isNetUrl) {
                Glide.with(context).asBitmap().load(images.get(position)).into(new SimpleTarget<Bitmap>() {
                    @Override
                    public void onResourceReady(@NonNull Bitmap resource, @Nullable Transition<? super Bitmap> transition) {
                        bitmap[0] = resource;
                        iv.setImageBitmap(resource);
                    }
                });

                iv.setOnLongClickListener(new View.OnLongClickListener() {
                    @Override
                    public boolean onLongClick(View v) {
                        if(bitmap.length > 0) {
                            showSaveDialog(bitmap[0]);
                        }
                        return false;
                    }
                });
//            } else {
//                iv.setImageURI(uri);
//            }
            container.addView(view);
            // 把当前添加ImageView返回回去.
            return view;
        }

        /**
         * 销毁一个条目
         * position 就是当前需要被销毁的条目的索引
         */
        @Override
        public void destroyItem(ViewGroup container, int position, Object object) {
            // 把ImageView从ViewPager中移除掉
            container.removeView((View) object);
        }

        @Override
        public int getItemPosition(Object object) {
            return POSITION_NONE;
        }

        AlertDialog dialog;

        private void showSaveDialog(Bitmap bitmap) {
            AlertDialog.Builder builder = new AlertDialog.Builder(PreviewImgActivity.this);
//        builder.setTitle("");
            builder.setMessage("保存到本机相册");

            //监听下方button点击事件
            builder.setPositiveButton("保存", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialogInterface, int i) {
                    getPermission(bitmap);
                }
            });

            builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    dialog.dismiss();
                }
            });

            //设置对话框是可取消的
            builder.setCancelable(false);
            dialog = builder.create();
            dialog.show();
        }
    }

    private void getPermission(Bitmap resource){
        AndPermission.with(this)
                .runtime()
                .permission(PermissionConstant.PERMISSIONS_OF_IMAGE)
                .onGranted(new Action<List<String>>() {
                    @Override
                    public void onAction(List<String> permissions) {
                        saveImg(resource);
                    }
                })
                .onDenied(new Action<List<String>>() {
                    @Override
                    public void onAction(List<String> permissions) {
                        Tips.showTips(PreviewImgActivity.this,"你已禁止访问相册权限");
                    }
                })
                .start();
    }

    private void saveImg(Bitmap image){
        boolean flag = ImgUtils.saveImage(PreviewImgActivity.this, Constants.DOWNLOAD_IMG_URL, System.currentTimeMillis()+".jpg", image);
        if(flag){
            Tips.showTips(PreviewImgActivity.this, "图片已保存到:"+Constants.DOWNLOAD_IMG_URL);
        } else {
            Tips.showTips(PreviewImgActivity.this, "图片保存失败");
        }
    }



    /** 记录次数 */
    private void recodeTimes(String id){
        String url = "api/clz/ma/touch";
        String jsonStr = "{\"id\""+":"+id+"}";
        OkGo.<String>post(App.getHttpUrl(url))
                .upJson(jsonStr)
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {

                    }
                });
    }
}
